package com.nju.bean.barrage;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

public class BarrageView extends LinearLayout {
	private Handler handler;

	public BarrageView(Context context) {
		super(context);
		setHandler();
	}

	private void setHandler() {
        handler = new Handler(this.getContext().getMainLooper()){
        	public void handleMessage(Message msg){
        		Barrage b = (Barrage) msg.obj;
        		b.move();
        		if(msg.arg1==1)
        			b.setVisibility(View.GONE);
        	}
        };
	}	
	
	public void addBarrage(String str){
		final Barrage b = new Barrage(this.getContext());
		b.setText(str);
		addView(b);
		new Timer().schedule(new TimerTask(){

			@Override
			public void run() {
				
				Message msg = new Message();
				msg.obj = b;
				if(!b.inScreen())
					msg.arg1 = 1;
				else
					msg.arg1 = 0;
				handler.sendMessage(msg);
				if(!b.inScreen())
					this.cancel();
			}}, 40,40);
	}
}




class Barrage extends TextView{
	private int speed = 5;
	public Barrage(Context context) {
		super(context);
		this.setLines(1);
		this.setPadding(480,0,0,0);
		this.setTextSize(36);
	}
	public void move(){
		this.setPadding(this.getPaddingLeft()-speed, 0, 0, 0);
	}
	public boolean inScreen(){
		if(this.getPaddingLeft()<-(this.getText().length()*30))
			return false;
		else
			return true;
	}
}